package com.dog.view.converter;

import com.dog.model.Applicant;
import com.dog.service.IApplicantService;
import com.dog.spring.ServiceFactory;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 * User: Kuttubek Aidaraliev
 * Date: 12.05.2010
 * Time: 13:08:20
 */
public class ApplicantConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        IApplicantService applicantService = ServiceFactory.getApplicantService();
        Applicant applicant = null;
        try {
            applicant = applicantService.get(new Long(s));
        } catch (Exception e){
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                    "Invalid Applicant selected. ");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }
        if(applicant == null){
            FacesMessage facesMessage = new FacesMessage("Conversation error occurred. ",
                        "Applicant not found. ");
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
            throw new ConverterException(facesMessage);
        }

        return applicant;

    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object o) {

        if(o instanceof Applicant) {
            Applicant applicant = (Applicant)o;
            return applicant.getId().toString();
        }
        else throw new IllegalArgumentException("Argument must be Applicant object!");
    }
}
